<template>
  <div class="app-container">
    <!-- 拓扑图组件 -->
    <el-dialog
      v-model="isShowTopology"
      title="拓扑图"
      class="topology-container"
      width="80%"
      destroy-on-close
      center
    >
      <indicator-topology :topology-id="topologyId" @back="handleTopologyBack" />
    </el-dialog>
    <!-- 左侧导航区域 -->
    <div class="left-bar-container">
      <!-- 暂定选择数据源位置 -->
      <el-select
        id="data-source-select"
        v-model="dataSourceId"
        class="data_source_box"
        placeholder="请选择连接池"
        @change="handleDataSourceSelectionChange"
      >
        <el-option
          v-for="item in fieldoptions"
          :key="item.id"
          :label="item.aliasName || item.dataSourceName"
          :value="item.id!"
        />
      </el-select>
      <!-- 搜索组件 -->
      <el-autocomplete
        id="search-keyword-input"
        v-model="searchKeyword"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入搜索内容（指标域、主题域、分组、指标等）"
        style="width: 100%; margin-bottom: 15px"
        @select="handleSearchSelect"
      />

      <!-- 添加清除搜索按钮 -->
      <el-button
        v-if="searchFilter.value"
        type="primary"
        size="small"
        style="width: 100%; margin-bottom: 15px"
        @click="resetSearchFilter"
      >
        清除搜索
      </el-button>

      <!-- 树形导航菜单 -->
      <el-row class="tac">
        <el-col :span="24">
          <!-- 外层指标域类型 -->
          <el-menu
            default-active="0"
            class="el-menu-vertical-demo"
            :unique-opened="true"
            @open="handleMenuOpen"
            @close="handleMenuClose"
          >
            <!-- 遍历各个指标域类型 -->
            <el-sub-menu
              v-for="type in filteredMetricDomainTypes"
              :key="type.id"
              :index="type.id"
              @contextmenu.prevent="handleMetricDomainRightClick($event, type.id)"
            >
              <template #title>
                <el-icon>
                  <location />
                </el-icon>
                <span class="submenu-title">{{ type.domainName }}</span>
              </template>

              <!-- 指标域下的指标分组 -->
              <template v-for="group in type.indicatorGroups" :key="group.id">
                <el-sub-menu :index="group.id" @contextmenu.stop.prevent>
                  <template #title>
                    <el-checkbox
                      v-if="showCheckboxes"
                      v-model="group.checked"
                      :indeterminate="group.indeterminate"
                      class="menu-checkbox"
                      @change="handleGroupCheckboxChange(group)"
                      @click.stop
                    />
                    {{ group.domainName }}
                  </template>
                  <el-menu-item
                    v-for="indicator in group.indicators"
                    :key="indicator.id"
                    :index="indicator.id"
                  >
                    <el-checkbox
                      v-if="showCheckboxes"
                      v-model="indicator.checked"
                      class="menu-checkbox"
                      @change="updateParentCheckboxState(group)"
                      @click.stop
                    />
                    {{ indicator.indicatorName }}
                  </el-menu-item>
                </el-sub-menu>
              </template>

              <!-- 指标域下的主题域 -->
              <template v-for="domain in type.themeDomains" :key="domain.id">
                <el-sub-menu
                  :index="'theme-' + domain.id"
                  @contextmenu.prevent="handleThemeDomainRightClick($event, type.id)"
                >
                  <template #title>
                    <el-checkbox
                      v-if="showCheckboxes && !isCreatingTable"
                      v-model="domain.checked"
                      :indeterminate="domain.indeterminate"
                      class="menu-checkbox"
                      @change="handleThemeDomainCheckboxChange(domain)"
                      @click.stop
                    />
                    <span class="submenu-title">{{ domain.domainName }}</span>
                  </template>
                  <el-menu-item
                    v-for="table in domain.themeTables"
                    :key="table.id"
                    :index="'table-' + table.id"
                  >
                    <el-checkbox
                      v-if="showCheckboxes && !isCreatingTable"
                      v-model="table.checked"
                      class="menu-checkbox"
                      @change="updateParentCheckboxState(domain)"
                      @click.stop
                    />
                    {{ table.tableName }}
                  </el-menu-item>
                </el-sub-menu>
              </template>
            </el-sub-menu>
          </el-menu>

          <!-- 右键上下文菜单 -->
          <div
            v-if="isContextMenuVisible"
            class="context-menu"
            :style="{ top: `${contextMenuY}px`, left: `${contextMenuX}px` }"
          >
            <!--右键指标域-->
            <template v-if="currentContextMenuType === 'metric-domain'">
              <p class="menu-item" @click="handleMenuAction('metric-domain-topology')">
                生成拓扑图
              </p>
              <p class="menu-item" @click="handleMenuAction('new-domain')">新建主题域</p>
              <p class="menu-item" @click="handleMenuAction('new-group')">新建分组</p>
            </template>
            <!--右键主题域-->
            <template v-else-if="currentContextMenuType === 'theme-domain'">
              <p class="menu-item" @click="handleMenuAction('new-table')">新建主题表</p>
              <p class="menu-item" @click="handleMenuAction('solidify')">指标固化</p>
              <p class="menu-item" @click="handleMenuAction('warning')">指标预警</p>
              <p class="menu-item" @click="handleMenuAction('theme_domain_topology')">
                指标体系拓扑图生成
              </p>
            </template>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content-container">
      <template v-if="!isCreatingDomain && !isCreatingTable">
        <div class="top-content-container">
          <el-input
            id="table-search-input"
            v-model="tableSearchKeyword"
            class="main-content-search"
            placeholder="搜索指标"
            clearable
            @change="handleSearch"
          />
          <div class="button-container">
            <el-button type="primary" @click="handleCreateIndicatorDomain">新建指标域</el-button>
            <el-button @click="createMetric">新建指标</el-button>
            <el-button danger @click="batchDelete">批量删除</el-button>
          </div>
        </div>
        <div class="table-container">
          <el-table
            ref="metricTableRef"
            v-loading="loading.metrics"
            :data="indicatorListResponse"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="序号" width="120" />
            <el-table-column prop="indicatorName" label="指标名称" width="300" />
            <el-table-column prop="domain" label="所属指标域" width="150" />
            <el-table-column prop="creator" label="创建人" width="150" />
            <el-table-column prop="createTime" label="创建时间" width="200" />
            <el-table-column label="操作" width="230">
              <template #default="{ row }">
                <el-button link type="primary" @click="showDetail(row)">详情</el-button>
                <el-button link type="info" @click="showEditForm(row)">编辑</el-button>
                <el-button link @click="testRun(row)">试运行</el-button>
                <el-button link @click="executeRun(row)">运行</el-button>
                <el-button link type="danger" @click="deleteItem(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </template>
      <!--      主题域右键菜单-->

      <!-- 新建主题表组件 -->
      <el-dialog
        v-model="isCreatingTable"
        title="新建主题表"
        :fullscreen="true"
        destroy-on-close
        center
      >
        <create-theme-table
          :data-source-id="dataSourceId"
          :data-source-name="dataSourceName"
          :domain-id="createTableDomainId"
          @success="handleSaveNewTable"
          @close="closedDialog"
        />
      </el-dialog>
      <!--      指标域右键菜单-->

      <!-- 新建主题域组件 -->
      <el-dialog v-model="isCreatingDomain" title="新建主题域" width="800px" destroy-on-close>
        <CreateThemeDomainList
          :data-source-id="dataSourceId"
          @save="handleSaveNewDomain"
          @cancel="handleCancelNewDomain"
        />
      </el-dialog>
      <!-- 新建域/分组组件 -->
      <el-dialog v-model="isCreateDomainGroups" title="新建分组" width="800px" destroy-on-close>
        <CreateDomainGroups
          :data-source-id="dataSourceId"
          :parent-id="parentId"
          @save="handleSaveNewGroups"
          @cancel="handleCancelNewGroups"
        />
      </el-dialog>
      <!-- 新建指标区分组件 -->
      <el-dialog v-model="isCreateTypeIndicator" width="400px" destroy-on-close>
        <div>
          <p>数据库</p>
          <el-button type="primary" size="large" @click="createIndicatorDataBase">
            根据数据库创建
          </el-button>
        </div>
        <div>
          <p>指标</p>
          <el-button type="success" size="large" @click="createByIndicator">根据指标创建</el-button>
        </div>
      </el-dialog>
      <!-- 根据数据库新建指标 -->
      <StrategyIndex v-if="isCreateingStrategyIndex" @cancel="handleCancelCreateTable" />
      <InsertIndicator v-if="isInsertIndicatorIndex" @cancel="handleCancelCreateTable" />
      <el-dialog v-model="dialogVisible" title="新建指标域" width="600px" destroy-on-close>
        <create-indicator-field
          :data-source-id="dataSourceId"
          mode="domain"
          @success="handleDialogSuccess"
          @close="dialogVisible = false"
        />
      </el-dialog>
    </div>

    <!-- 运行结果对话框 -->
    <el-dialog v-model="resultDialogVisible" title="运行结果" width="800px" destroy-on-close>
      <el-table
        v-if="indicatorOperationalResponse && indicatorOperationalResponse.fileNames"
        :data="indicatorOperationalResponse.entityList || []"
        style="width: 100%"
      >
        <el-table-column
          v-for="fileName in indicatorOperationalResponse.fileNames"
          :key="fileName"
          :prop="fileName"
          :label="fileName"
        />
      </el-table>
      <div v-else-if="indicatorOperationalResponse" class="no-data">暂无数据</div>
      <div v-else class="loading">加载中...</div>
    </el-dialog>

    <!-- 指标详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="指标详情" width="800px" destroy-on-close>
      <indicator-detail v-if="indicatorDetailId" :indicator-id="indicatorDetailId" />
      <div v-else class="no-data">暂无指标详情数据</div>
    </el-dialog>
    <!-- 编辑指标对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑指标" width="600px" destroy-on-close>
      <el-form ref="editFormRef" :model="indicatorEditInfo" :rules="rules" label-width="120px">
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="indicatorEditInfo.indicatorName" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="异常规则" prop="abnormalId">
          <el-select v-model="indicatorEditInfo.abnormalId" placeholder="请选择异常规则">
            <el-option
              v-for="item in abnormalRules"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="saveEditForm(indicatorEditInfo)">保存</el-button>
        </el-form-item>
      </el-form>
      <!-- <el-table ref="metricTableRef" v-loading="loading.metrics" :data="indicatorEditInfo" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="120" />
        <el-table-column prop="indicatorName" label="指标名称" width="300" />
        <el-table-column prop="domain" label="所属指标域" width="150" />
        <el-table-column prop="abnormalId" label="指标异常规则" width="150">
          <template #default="{ row }">
            <el-select v-model="row.abnormalId" placeholder="请选择指标异常规则">
              <el-option v-for="item in abnormalRules" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230">
          <template #default="{ row }">
            <el-button link type="info" @click="saveEditForm(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table> -->
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default { name: "IndicationManage" };
</script>

<script setup lang="ts">
import { ref, computed, onUnmounted } from "vue";
import { Location, Message } from "@element-plus/icons-vue";
import IndicatorDetail from "./detail/index.vue";
import IndicatorTopology from "./component/indicatorTopology.vue";
import NewDomainList from "./component/newDomain.vue";
import StrategyIndex from "../strategy/strategy-index/insert-database/index.vue";
import InsertIndicator from "../strategy/strategy-index/insert-indicator/index.vue";
import NewThematicList from "./themeDomainComponent/newThematicList.vue";
import CreateThemeDomainList from "./indicatorDomainComponent/createThemeDomain.vue";
import CreateIndicatorField from "@/views/dataSourceManage/component/createIndicatorField.vue";
import CreateDomainGroups from "./component/createDomainGroups.vue";
import CreateThematicList from "./themeDomainComponent/createThematicList.vue";
import CreateThemeTable from "./themeDomainComponent/createThemeTable.vue";
import { ElMessage } from "element-plus";
import { onMounted } from "vue";
import { IndicationAPI, IndicationTable } from "@/api/indicationManage"; // 引入 IndicationAPI
import IndicatorManageAPI, { DataSourceList } from "@/api/strategy/strategy-index-database";
import IndicatorDomainAPI, {
  DomainListParameter,
  DomainGroupsTreeReponse,
  DomainGroupInsertParameter,
  IndicatorGroupsTree,
  IndicatorChildren,
} from "@/api/indicationManage/domain";
import IndicatorAPI, {
  IndicatorListParameter,
  IndicatorListResponse,
  IdListParameter,
  IndicatorOperationalResponse,
  IndicatorTopologyResponse,
  IndicatorInfoResponse,
  AbnormalRuleResponse,
  IndicatorAbnormalInfoResponse,
  UpdateByIdForAbnormalParameter,
} from "@/api/indicationManage/indexNew";

defineOptions({
  name: "IndicationManage",
  inheritAttrs: false,
});

const router = useRouter();
const route = useRoute();
const dataSourceId = ref();
const fieldoptions = ref<DataSourceList[]>();
const domainListParameter = reactive<DomainListParameter>({});
const domainGroupInsertParameter = reactive<DomainGroupInsertParameter>({});
const metricDomainTypesNew = ref<DomainGroupsTreeReponse>();
const indicatorListParameter = reactive<IndicatorListParameter>({});
const indicatorListResponse = ref<IndicatorListResponse[]>();
const idsParamter = reactive<IdListParameter>({});
const indicatorOperationalResponse = ref<IndicatorOperationalResponse>({});
const indicatorTopologyParam = reactive<IndicatorListParameter>({});
// 指标详情--包含异常规则
const indicatorEditInfo = ref<IndicatorAbnormalInfoResponse>({});
// 结果对话框可见性
const resultDialogVisible = ref(false);
// 编辑对话框可见性
const editDialogVisible = ref(false);

// 指标详情ID
const indicatorDetailId = ref<number | undefined>(undefined);

// 指标异常规则列表
const abnormalRules = ref<AbnormalRuleResponse[]>([]);

// 编辑指标--保存参数
const updateByIdForAbnormalParameter = reactive<UpdateByIdForAbnormalParameter>({});

// 定义分页查询参数类型
interface TableDataPageQuery {
  pageNum: number;
  pageSize: number;
  keyword?: string; // 可选字段
}
// 分页查询参数
const queryParams = ref<TableDataPageQuery>({
  pageNum: 1,
  pageSize: 10,
  keyword: "", // 与搜索框绑定
});

const total = ref(0); // 总条目数

// 在 setup 中添加数据获取逻辑
onMounted(async () => {
  // await loadTableData();
  handleQuery().then(() => {
    if (route.query.dataSourceId) {
      dataSourceId.value = route.query.dataSourceId;
      handleDataSourceSelectionChange(dataSourceId.value);
    }
  });
});

// 添加 onActivated 钩子，确保缓存组件激活时重新加载数据
onActivated(() => {
  if (dataSourceId.value) {
    handleDataSourceSelectionChange(dataSourceId.value);
  }
  // 如果需要每次激活都重新加载表格数据，可以取消下面这行注释
  // loadTableData();
});

// 添加搜索处理
const handleSearch = () => {
  queryParams.value.pageNum = 1; // 搜索时重置到第一页
  // loadTableData();
};

// 加载数据源列表
async function handleQuery() {
  fieldoptions.value = await IndicatorManageAPI.DataSourceList();
}

const dataSourceName = ref();

// 错误处理
const handleError = (err: any) => {
  if (err.response) {
    ElMessage.error(`数据加载失败: ${err.response.data.message}`);
  } else if (err.request) {
    ElMessage.error("请求未收到响应，请检查网络连接");
  } else {
    ElMessage.error("请求失败，请稍后重试");
  }
};

// 统一的数据加载方法
const loadTableData = async () => {
  console.log("请求参数:", queryParams.value);
  try {
    loading.value.metrics = true;
    const response = await IndicationAPI.tableDataQuery({
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      keyword: queryParams.value.keyword?.trim(), // 传递搜索关键字
    });
    tableData.value = response.data.records.map((item, index) => ({
      ...item,
      index: (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1,
    }));
    total.value = response.data.total;
  } catch (err) {
    handleError(err);
  } finally {
    loading.value.metrics = false;
  }
};

// 分页大小变化
const handleSizeChange = (newSize: number) => {
  queryParams.value.pageSize = newSize;
  queryParams.value.pageNum = 1; // 重置到第一页
  // loadTableData();
};

// 页码变化
const handlePageChange = (newPage: number) => {
  queryParams.value.pageNum = newPage;
  // loadTableData();
};

const dialogVisible = ref(false);

// 处理新建指标域
function handleCreateIndicatorDomain() {
  dialogVisible.value = true;
}

// 处理对话框提交成功
const handleDialogSuccess = () => {
  dialogVisible.value = false;
  // loadTableData(); // 刷新表格数据
  handleDataSourceSelectionChange(dataSourceId.value);
  ElMessage.success("创建成功");
};

// 类型定义
type MenuItem = {
  id: string;
  title: string;
  checked: boolean;
  children?: MenuItem[];
  indeterminate?: boolean;
};

type ThemeDomain = {
  id: string;
  name: string;
  checked: boolean;
  indeterminate: boolean;
  tables: {
    id: string;
    name: string;
    checked: boolean;
  }[];
};

type MetricDomainType = {
  id: string;
  name: string;
  indicatorGroups: Array<{
    id: string;
    title: string;
    checked: boolean;
    indeterminate: boolean;
    children?: Array<{
      id: string;
      title: string;
      checked: boolean;
    }>;
  }>;
  themeDomains: Array<{
    id: string;
    name: string;
    checked: boolean;
    indeterminate: boolean;
    tables: Array<{
      id: string;
      name: string;
      checked: boolean;
    }>;
  }>;
};

type MetricItem = {
  id: number;
  index: string;
  name: string;
  domain: string;
  creator: string;
  createTime: string;
};

type SelectedItem = {
  id: string;
  name: string;
  type: "metric" | "table";
};

// 在原有类型定义后添加接口响应类型
interface ApiResponse<T> {
  code: number;
  data: T;
}

// 组件引用
const metricTableRef = ref();

// 响应式数据
const searchKeyword = ref("");
const tableSearchKeyword = ref(queryParams.value.keyword);
// 搜索结果相关状态已移除，因为不再使用搜索结果面板
// 拓扑图相关
const isShowTopology = ref(false);
const topologyData = ref<IndicatorTopologyResponse>({});

// 处理返回事件
const handleTopologyBack = () => {
  isShowTopology.value = false;
};

// 关闭搜索结果面板函数已移除，因为不再使用搜索结果面板
const selectedItems = ref<MetricItem[]>([]);
const selectedMetrics = ref<SelectedItem[]>([]);
const isCreatingDomain = ref(false);
const isCreateDomainGroups = ref(false);
const parentId = ref<string | null>(null);
const isCreateTypeIndicator = ref(false);
const isCreateingStrategyIndex = ref(false);
const isInsertIndicatorIndex = ref(false);
const isCreatingTable = ref(false);
const createTableDomainId = ref<string | null>(null);
const showCheckboxes = ref(false);
const newDomainForm = ref({ name: "" });
const newTableForm = ref({ name: "" });
const isContextMenuVisible = ref(false);
const contextMenuX = ref(0);
const contextMenuY = ref(0);
const currentContextMenuType = ref<"metric-domain" | "theme-domain">("metric-domain");
// 当前右键点击的主题域id
const currentThemeDomainId = ref<string | null>(null);
const indicatorGroupsTree = ref<IndicatorGroupsTree[]>();

// 新增计算属性 (修改后)
const filteredMetricDomainTypes = computed(() => {
  indicatorGroupsTree.value = metricDomainTypesNew.value?.indicatorList;
  if (isCreatingTable.value && currentMetricDomainType.value) {
    return indicatorGroupsTree.value?.filter(
      (type: any) => type.id === currentMetricDomainType.value
    );
  }
  return indicatorGroupsTree.value;
});

const tableData = ref<IndicationTable[]>([]);

// 添加加载状态
const loading = ref({
  domains: false,
  metrics: false,
});

// 添加错误处理
const error = ref({
  domains: null,
  metrics: null as Error | null,
});

// 处理取消创建主题表
const handleCancelCreateTable = () => {
  isCreatingTable.value = false;
  currentMetricDomainType.value = null; // 新增重置代码
  showCheckboxes.value = false;
};

// 删除时清除选中状态
const handleRemoveItem = (itemId: string) => {
  const clearChecks = (nodes: any[]) => {
    nodes.forEach((node) => {
      if (node.id === itemId) node.checked = false;
      if (node.children) clearChecks(node.children);
      if (node.tables) clearChecks(node.tables);
    });
  };
};

// 复选框逻辑
const handleGroupCheckboxChange = (group: MenuItem) => {
  if (group.children) {
    group.children.forEach((child) => (child.checked = group.checked));
  }
  updateParentCheckboxState(group);
};

const handleThemeDomainCheckboxChange = (domain: ThemeDomain) => {
  if (domain.tables) {
    domain.tables.forEach((table) => (table.checked = domain.checked));
  }
  updateParentCheckboxState(domain);
};

const updateParentCheckboxState = (node: any) => {
  if (node.children || node.tables) {
    const children = node.children || node.tables;
    const checkedCount = children.filter((child: any) => child.checked).length;
    if (checkedCount === 0) {
      node.checked = false;
      node.indeterminate = false;
    } else if (checkedCount === children.length) {
      node.checked = true;
      node.indeterminate = false;
    } else {
      node.checked = false;
      node.indeterminate = true;
    }
  }
};

// 右键菜单及其它事件处理
const showContextMenu = (event: MouseEvent, menuType: "metric-domain" | "theme-domain") => {
  const { clientX, clientY } = event;
  const { innerWidth: winWidth, innerHeight: winHeight } = window;
  const menuWidth = 180;
  const menuHeight = 120;
  contextMenuX.value = clientX + menuWidth > winWidth ? winWidth - menuWidth : clientX;
  contextMenuY.value = clientY + menuHeight > winHeight ? winHeight - menuHeight : clientY;
  currentContextMenuType.value = menuType;
  isContextMenuVisible.value = true;
  document.addEventListener("click", hideContextMenu);
};

const hideContextMenu = () => {
  isContextMenuVisible.value = false;
  document.removeEventListener("click", hideContextMenu);
};

onUnmounted(() => {
  document.removeEventListener("click", hideContextMenu);
});

function convertKeyToNumber(key: string): number | null {
  // 尝试直接转换
  let num = Number(key);
  if (!isNaN(num)) {
    return num;
  }

  // 提取字符串中的数字部分
  const match = key.match(/\d+/);
  if (match) {
    const numberPart = match[0];
    return Number(numberPart);
  }

  // 如果都无法转换，返回 null
  return null;
}

// 添加一个标志位来控制是否需要加载数据
const needReloadData = ref(true);

const handleMenuOpen = async (key: string, path: string[]) => {
  console.log("菜单展开:", key, path);
  // 每次展开菜单时加载数据
  const id = convertKeyToNumber(key);
  indicatorListParameter.id = id!;
  handleQueryIndicatorList(indicatorListParameter);
};

const handleMenuClose = async (key: string, path: string[]) => {
  console.log("菜单收起:", key, path);
  // 菜单关闭时不需要加载数据
};

// 在数据源变化时重置标志位，确保数据会重新加载
async function handleDataSourceSelectionChange(id: number) {
  domainGroupInsertParameter.dataSourceId = dataSourceId.value;
  dataSourceName.value = fieldoptions.value?.find((item) => item.id === id)?.dataSourceName;
  const response = await IndicatorDomainAPI.SelectDomainTree(domainGroupInsertParameter);
  metricDomainTypesNew.value = response;
  needReloadData.value = true; // 重置标志位
}

const handleQueryIndicatorList = async (indicatorListParameter: IndicatorListParameter) => {
  await IndicatorAPI.List(indicatorListParameter).then((data) => {
    indicatorListResponse.value = data;
  });
};

const handleSelectionChange = (items: MetricItem[]) => {
  selectedItems.value = items;
};

const handleMenuAction = (action: string) => {
  const actionMap = {
    "metric-domain-topology": "生成拓扑图",
    "new-domain": "新建主题域",
    "new-group": "新建分组",
    "new-table": "新建主题表",
    solidify: "指标固化",
    warning: "指标预警",
    topology2: "指标体系拓扑图生成",
  };
  console.log(`执行${actionMap[action]}操作`);
  switch (action) {
    case "metric-domain-topology":
      generateTopology2();
      break;
    case "new-domain":
      createMetricDomain();
      break;
    case "new-group":
      createMetricGroup();
      break;
    case "new-table":
      handleCreateMetricTable();
      break;
    case "solidify":
      handleSolidifyMetric();
      break;
    case "warning":
      handleSetWarning();
      break;
    // case "topology2":
    //   generateTopology2();
    //   break;
  }
  hideContextMenu();
};

const createMetricDomain = () => {
  isCreatingDomain.value = true;
  isCreatingIndicatorField.value = true;
};

const createMetric = () => {
  isCreateTypeIndicator.value = true;
};
const createIndicatorDataBase = () => {
  router.push({
    name: "InsertDatabase",
    query: {
      dataSourceId: dataSourceId.value,
    },
  });
};

const createByIndicator = () => {
  router.push({
    name: "InsertIndicator",
    query: {
      dataSourceId: dataSourceId.value,
    },
  });
};

const createMetricGroup = () => {
  parentId.value = currentMetricDomainType.value;
  isCreateDomainGroups.value = true;
  console.log("当前菜单ID:", currentMetricDomainType.value);
};

const handleCreateMetricTable = () => {
  isCreatingTable.value = true;
  // showCheckboxes.value = true;
  hideContextMenu();
  createTableDomainId.value = currentMetricDomainType.value;
};

// 新建主题表成功后，关闭弹窗
const handleSaveNewTable = (themeTableData: { dataSourceId: number }) => {
  metricDomainTypesNew.value?.indicatorList.forEach((type: any) => {
    if (type.id === currentMetricDomainType.value) {
      type.themeDomains.push({
        // id: domainData.id,
        // name: domainData.name,
        dataSourceId: themeTableData.dataSourceId,
        checked: false,
        indeterminate: false,
        tables: [],
      });
    }
  });
  isCreatingTable.value = false;
  handleDataSourceSelectionChange(dataSourceId.value);
};

const closedDialog = (themeTableData: { dataSourceId: number }) => {
  metricDomainTypesNew.value?.indicatorList.forEach((type: any) => {
    if (type.id === currentMetricDomainType.value) {
      type.themeDomains.push({
        // id: domainData.id,
        // name: domainData.name,
        dataSourceId: themeTableData.dataSourceId,
        checked: false,
        indeterminate: false,
        tables: [],
      });
    }
  });
  isCreatingTable.value = false;
  handleDataSourceSelectionChange(dataSourceId.value);
};

const handleSolidifyMetric = () => {
  console.log("执行指标固化操作");
};

const handleSetWarning = () => {
  console.log("设置指标预警");
};

const generateTopology1 = () => {
  console.log("生成拓扑图");
};

// 简化的拓扑图生成方法，只负责传递ID和显示对话框
const generateTopology2 = () => {
  console.log("指标体系拓扑图生成");
  console.log("当前菜单ID:", currentMetricDomainType.value);

  if (currentMetricDomainType.value) {
    // 设置拓扑图ID参数
    topologyId.value = currentMetricDomainType.value;
    // 显示拓扑图对话框
    isShowTopology.value = true;
  }
};

// 拓扑图ID参数
const topologyId = ref<string | number | null>(null);

const batchDelete = async () => {
  idsParamter.ids = [] as number[];
  selectedItems.value.map((item) => {
    idsParamter.ids?.push(item.id);
  }) as unknown as number[];
  try {
    await IndicatorAPI.Delete(idsParamter);
    ElMessage.success("删除成功");
    handleQueryIndicatorList(indicatorListParameter);
  } catch (error) {
    ElMessage.warning("删除失败");
  }
  console.log("批量删除选中项:", idsParamter.ids);
};

// 指标详情相关响应式数据
const detailDialogVisible = ref(false);
const indicatorDetail = ref<IndicatorInfoResponse | null>(null);

// 查看指标详情
const showDetail = (row: MetricItem) => {
  detailDialogVisible.value = true;
  indicatorDetailId.value = row.id;
  indicatorDetail.value = null; // 重置详情数据，等待子组件加载
};

// 编辑指标
const showEditForm = async (row: MetricItem) => {
  editDialogVisible.value = true;
  // 指标异常规则列表
  await IndicatorAPI.AbnormalRules()
    .then((res) => {
      abnormalRules.value = res;
    })
    .catch((error) => {
      ElMessage.warning("获取指标异常规则失败");
    });
  // 指标详情
  await IndicatorAPI.IndicatorEditInfo({ id: row.id })
    .then((res) => {
      indicatorEditInfo.value = res;
    })
    .catch((error) => {
      ElMessage.warning("获取指标详情失败");
      console.error("获取指标详情失败:", error);
    });
};

// 编辑指标--保存
const saveEditForm = async (row: IndicatorAbnormalInfoResponse) => {
  updateByIdForAbnormalParameter.id = row.id;
  updateByIdForAbnormalParameter.indicatorName = row.indicatorName;
  updateByIdForAbnormalParameter.abnormalId = row.abnormalId;
  await IndicatorAPI.UpdateByIdForAbnormal(updateByIdForAbnormalParameter)
    .then(() => {
      ElMessage.success("更新指标异常规则成功");
    })
    .catch((error) => {
      ElMessage.warning("更新指标异常规则失败");
    });
  editDialogVisible.value = false;
};

const testRun = async (row: MetricItem) => {
  indicatorListParameter.id = row.id;
  try {
    const data = await IndicatorAPI.TestRun(indicatorListParameter);
    // 确保数据结构正确
    if (data) {
      indicatorOperationalResponse.value = data;
      // 强制更新响应式数据
      indicatorOperationalResponse.value = { ...data };
      // 显示结果对话框
      resultDialogVisible.value = true;
    } else {
      // 处理数据为空的情况
      indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
      resultDialogVisible.value = true;
      ElMessage.warning("未获取到运行结果数据");
    }
  } catch (error) {
    handleError(error);
    // 确保对话框可以关闭
    indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
    resultDialogVisible.value = true;
  }
  console.log("运行结果:", indicatorOperationalResponse.value);
  console.log("运行:", row);
};

const executeRun = async (row: MetricItem) => {
  indicatorListParameter.id = row.id;
  try {
    const data = await IndicatorAPI.Operational(indicatorListParameter);
    // 确保数据结构正确
    if (data) {
      indicatorOperationalResponse.value = data;
      // 强制更新响应式数据
      indicatorOperationalResponse.value = { ...data };
      // 显示结果对话框
      resultDialogVisible.value = true;
    } else {
      // 处理数据为空的情况
      indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
      resultDialogVisible.value = true;
      ElMessage.warning("未获取到运行结果数据");
    }
  } catch (error) {
    handleError(error);
    // 确保对话框可以关闭
    indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
    resultDialogVisible.value = true;
  }
  console.log("运行结果:", indicatorOperationalResponse.value);
  console.log("运行:", row);
};

const deleteItem = async (row: MetricItem) => {
  idsParamter.ids = [] as number[];
  idsParamter.ids.push(row.id);
  try {
    await IndicatorAPI.Delete(idsParamter);
    ElMessage.success("删除成功");
    handleQueryIndicatorList(indicatorListParameter);
  } catch (error) {
    ElMessage.warning("删除失败");
  }
  console.log("删除:", row.id);
};

// 搜索关键词状态
const searchFilter = ref("");

// 修改搜索函数，只搜索域名
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  if (!queryString || !metricDomainTypesNew.value?.indicatorList) {
    searchFilter.value = "";
    cb([]);
    return;
  }

  searchFilter.value = queryString.toLowerCase();
  const suggestions = [];
  const lowerQuery = queryString.toLowerCase();

  // 只搜索指标域类型
  metricDomainTypesNew.value.indicatorList.forEach((type: any) => {
    if (type.domainName.toLowerCase().includes(lowerQuery)) {
      suggestions.push({
        value: type.domainName,
        label: `指标域: ${type.domainName}`,
        type: "metric-domain",
        id: type.id,
      });
    }

    // 搜索指标域下的主题域
    if (type.themeDomains) {
      type.themeDomains.forEach((domain: any) => {
        if (domain.domainName.toLowerCase().includes(lowerQuery)) {
          suggestions.push({
            value: domain.domainName,
            label: `主题域: ${domain.domainName}`,
            type: "theme-domain",
            id: domain.id,
            parentId: type.id,
          });
        }
      });
    }
  });

  cb(suggestions);
};

// 重置搜索过滤器
const resetSearchFilter = () => {
  searchFilter.value = "";
  searchKeyword.value = "";
};

const handleSearchSelect = (item: any) => {
  console.log("选中搜索结果:", item);

  // 根据选中项的类型设置搜索过滤器
  switch (item.type) {
    case "metric-domain":
    case "theme-domain":
      searchFilter.value = item.value.toLowerCase();
      break;
    default:
      break;
  }
};

// 搜索结果相关状态已在文件上方声明

// 关闭搜索结果面板函数已移除，因为不再使用搜索结果面板

const filteredTableData = computed(() => {
  // 改为服务端搜索，这里只需返回原始数据
  return tableData.value;
});

const currentMetricDomainType = ref<string | null>(null);

// 新增：右键点击指标域显示指标域右键菜单
const handleMetricDomainRightClick = (event: MouseEvent, typeId: string) => {
  event.stopPropagation();
  currentMetricDomainType.value = typeId;
  showContextMenu(event, "metric-domain");
};

// 新增：右键点击主题域显示主题域右键菜单，并阻止事件冒泡
const handleThemeDomainRightClick = (event: MouseEvent, typeId: string) => {
  event.stopPropagation();
  currentMetricDomainType.value = typeId;
  showContextMenu(event, "theme-domain");
};

// 处理新建主题域保存
const handleSaveNewDomain = (domainData: { name: string; id: string; dataSourceId: number }) => {
  metricDomainTypesNew.value?.indicatorList.forEach((type: any) => {
    if (type.id === currentMetricDomainType.value) {
      type.themeDomains.push({
        id: domainData.id,
        name: domainData.name,
        dataSourceId: domainData.dataSourceId,
        checked: false,
        indeterminate: false,
        tables: [],
      });
    }
  });
  isCreatingDomain.value = false;
  // 刷新菜单列表
  handleDataSourceSelectionChange(dataSourceId.value);
};

const handleSaveNewGroups = (domainData: { name: string; id: string; dataSourceId: number }) => {
  metricDomainTypesNew.value?.indicatorList.forEach((type: any) => {
    if (type.id === currentMetricDomainType.value) {
      type.themeDomains.push({
        id: domainData.id,
        name: domainData.name,
        dataSourceId: domainData.dataSourceId,
        checked: false,
        indeterminate: false,
        tables: [],
      });
    }
  });
  isCreateDomainGroups.value = false;
  // 刷新菜单列表
  handleDataSourceSelectionChange(dataSourceId.value);
};

// 处理取消新建主题域
const handleCancelNewDomain = () => {
  isCreatingDomain.value = false;
};

const handleCancelNewGroups = () => {
  isCreateDomainGroups.value = false;
};

// 新增响应式数据
const isCreatingIndicatorField = ref(false);

// 新增 handleCancelCreateIndicatorField 方法
const handleCancelCreateIndicatorField = () => {
  isCreatingIndicatorField.value = false;
};

const handleSubmitSuccess = () => {
  isCreatingTable.value = false;
};
</script>

<style scoped lang="scss">
.no-data,
.loading {
  padding: 20px;
  color: #909399;
  text-align: center;
}

.detail-content {
  padding: 10px 0;
}

.el-form-item {
  margin-bottom: 15px;
}

.no-data {
  padding: 20px;
  color: #909399;
  text-align: center;
}

.el-table {
  margin-top: 10px;
}

.el-dialog__body {
  max-height: 600px;
  padding: 20px;
  overflow: auto;
}

.app-container {
  display: flex;
  // min-height: 100vh;
}

.topology-container {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.95);
}

.left-bar-container {
  flex: 0 0 200px;
  padding: 16px;
  margin-right: 16px;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);

  .el-menu {
    border-right: none;
  }

  .menu-checkbox {
    margin-right: 8px;
  }
}

.main-content-container {
  flex: 1;
  width: calc(100% - 200px);
  padding: 16px;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
}

.top-content-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .main-content-search {
    flex: 0 0 320px;
  }

  .button-container {
    margin-left: auto;

    .el-button + .el-button {
      margin-left: 8px;
    }
  }
}

.data_source_box {
  margin-bottom: 12px;
}

.table-container {
  width: 100%;

  :deep(.el-table) {
    width: 100%;

    th.el-table__cell {
      background-color: var(--el-fill-color-light);
    }

    .el-button {
      padding: 0;

      + .el-button {
        margin-left: 8px;
      }
    }
  }
}

.context-menu {
  position: fixed;
  z-index: 9999;
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);

  .menu-item {
    padding: 8px 16px;
    font-size: var(--el-font-size-base);
    color: var(--el-text-color-regular);
    transition: background-color 0.2s;

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    + .menu-item {
      border-top: 1px solid var(--el-border-color-light);
    }
  }
}

.domain-creation-container {
  padding: 24px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);

  .creation-title {
    margin-bottom: 24px;
    color: var(--el-text-color-primary);
  }

  .selected-items {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}

.menu-checkbox {
  margin-right: 8px;
  vertical-align: middle;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.tree-node-content {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.node-content {
  margin-top: 3px;
  font-size: 12px;
  color: #606266;
  word-break: break-all;
}

.no-search-results {
  padding: 20px 0;
  color: #909399;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 15px;
}

// 修复CSS中的格式问题
.el-menu-item {
  padding: 0;

  + .el-button {
    margin-left: 8px;
  }
}
</style>
